#!/bin/sh
#
# sal -- Simple application launcher.
#
# Copyright (C) 2024  Ricardo García Jiménez <ricardogj08@riseup.net>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.
#

# Mapa de teclas.
key() {
  case $1 in
    del)
      printf '\177'
      ;;
    esc)
      printf '\033'
      ;;
  esac
}

# Acciones de la terminal.
terminal() {
  case $1 in
    clear)
      printf '\033c'
      ;;
  esac
}

# Busca un ejecutable desde un patrón de búsqueda.
search() {
  set -f

  pattern="$1"

  old_ifs=${IFS}

  IFS=:

  # shellcheck disable=2086
  set -- $PATH

  [ -n "${pattern}" ] &&
    find "$@" ! -type d -name "${pattern}*" 2>/dev/null

  IFS=${old_ifs}

  set +f

  unset pattern
}

# Lee un solo caracter desde la terminal.
sread() {
  stty -icanon -echo

  dd ibs=1 count=1 2>/dev/null

  stty icanon echo
}

# Función principal de la aplicación.
main() {
  action=''

  while :; do
    input=$(sread)

    terminal clear

    case $input in
      "$(key del)")
        action=${action%?}
        ;;
      "$(key esc)")
        break
        ;;
      *)
        action=${action}${input}
        ;;
    esac

    search "${action}"
  done
}

main "$@"
